/**
 * 人脸识别摄像头组件
 * 提供摄像头调用、图片捕获、实时预览等功能
 */

import React, { useRef, useEffect, useState, useCallback } from 'react'
import { Button, Toast } from 'antd-mobile'
import { CameraOutline, CloseOutline } from 'antd-mobile-icons'
import './FaceCamera.css'

interface FaceCameraProps {
  onCapture: (imageData: string) => void
  onClose: () => void
  isVisible: boolean
  title?: string
}

const FaceCamera: React.FC<FaceCameraProps> = ({
  onCapture,
  onClose,
  isVisible,
  title = '人脸识别'
}) => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const streamRef = useRef<MediaStream | null>(null)
  
  const [isStreaming, setIsStreaming] = useState(false)
  const [isCapturing, setIsCapturing] = useState(false)
  const [error, setError] = useState<string>('')

  // 启动摄像头
  const startCamera = useCallback(async () => {
    try {
      setError('')
      
      // 请求摄像头权限
      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          width: { ideal: 640 },
          height: { ideal: 480 },
          facingMode: 'user' // 前置摄像头
        },
        audio: false
      })

      streamRef.current = stream
      
      if (videoRef.current) {
        videoRef.current.srcObject = stream
        videoRef.current.play()
        setIsStreaming(true)
      }
    } catch (err) {
      console.error('摄像头启动失败:', err)
      setError('无法访问摄像头，请检查权限设置')
      Toast.show('无法访问摄像头，请检查权限设置')
    }
  }, [])

  // 停止摄像头
  const stopCamera = useCallback(() => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(track => track.stop())
      streamRef.current = null
    }
    setIsStreaming(false)
  }, [])

  // 捕获图片
  const captureImage = useCallback(() => {
    if (!videoRef.current || !canvasRef.current || isCapturing) {
      return
    }

    setIsCapturing(true)
    
    try {
      const video = videoRef.current
      const canvas = canvasRef.current
      const ctx = canvas.getContext('2d')
      
      if (!ctx) {
        throw new Error('无法获取画布上下文')
      }

      // 设置画布尺寸
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      
      // 绘制当前视频帧到画布
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      
      // 转换为Base64
      const imageData = canvas.toDataURL('image/jpeg', 0.8)
      
      // 调用回调函数
      onCapture(imageData)
      
      Toast.show('图片捕获成功')
    } catch (err) {
      console.error('图片捕获失败:', err)
      Toast.show('图片捕获失败，请重试')
    } finally {
      setIsCapturing(false)
    }
  }, [onCapture, isCapturing])

  // 组件挂载时启动摄像头
  useEffect(() => {
    if (isVisible) {
      startCamera()
    } else {
      stopCamera()
    }
    
    // 组件卸载时清理资源
    return () => {
      stopCamera()
    }
  }, [isVisible, startCamera, stopCamera])

  // 处理窗口关闭
  const handleClose = () => {
    stopCamera()
    onClose()
  }

  if (!isVisible) {
    return null
  }

  return (
    <div className="face-camera-overlay">
      <div className="face-camera-container">
        {/* 头部 */}
        <div className="face-camera-header">
          <h3 className="face-camera-title">{title}</h3>
          <Button
            className="face-camera-close-btn"
            onClick={handleClose}
            fill="none"
            size="small"
          >
            <CloseOutline />
          </Button>
        </div>

        {/* 视频预览区域 */}
        <div className="face-camera-preview">
          {error ? (
            <div className="face-camera-error">
              <p>{error}</p>
              <Button
                color="primary"
                onClick={startCamera}
                style={{ marginTop: '16px' }}
              >
                重试
              </Button>
            </div>
          ) : (
            <>
              <video
                ref={videoRef}
                className="face-camera-video"
                autoPlay
                playsInline
                muted
              />
              
              {/* 人脸识别框 */}
              <div className="face-camera-guide">
                <div className="face-guide-frame">
                  <div className="face-guide-corners">
                    <div className="corner top-left"></div>
                    <div className="corner top-right"></div>
                    <div className="corner bottom-left"></div>
                    <div className="corner bottom-right"></div>
                  </div>
                  <div className="face-guide-text">
                    请将人脸对准框内
                  </div>
                </div>
              </div>
            </>
          )}
        </div>

        {/* 控制按钮 */}
        <div className="face-camera-controls">
          <Button
            className="face-camera-capture-btn"
            color="primary"
            size="large"
            onClick={captureImage}
            disabled={!isStreaming || isCapturing}
            loading={isCapturing}
          >
            <CameraOutline />
            {isCapturing ? '拍摄中...' : '拍摄'}
          </Button>
        </div>

        {/* 使用说明 */}
        <div className="face-camera-tips">
          <p>• 请确保光线充足</p>
          <p>• 保持人脸正面面对摄像头</p>
          <p>• 避免遮挡面部特征</p>
        </div>

        {/* 隐藏的画布，用于图片处理 */}
        <canvas
          ref={canvasRef}
          style={{ display: 'none' }}
        />
      </div>
    </div>
  )
}

export default FaceCamera
